package org.gwt.grin.client.features;

import java.util.Map;

import org.gwt.grin.client.Feature;
import org.gwt.grin.client.util.FontSpec;
import org.gwt.grin.client.util.Graphics;
import org.gwt.grin.client.util.Rectangle;

import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class Text extends Box implements HasHorizontalAlignment /*
																 * TODO change
																 * that so that
																 * we can use
																 * justify too
																 */{

	protected String text;
	protected boolean wordWrap;
	protected FontSpec fontSpec;
	protected int lineHeight;
	protected HorizontalAlignmentConstant textAlign;

	private Label widget;

	public Text(String name) {
		super(name);
	}
	
	@Override
	protected Feature createClone(Map<Feature, Feature> clones) {
		if (!isSetup() || isActivated) {
			throw new IllegalStateException();
		}
		Text result = new Text(null);
		result.show = show; // FIXME
		result.setup(x, y, width, height, outlineWidth, outlineColor,
				fillColor, bgImage, null);
		if (scaledBounds != null) {
			result.scaledBounds = new Rectangle(scaledBounds);
		}
		result.text = text;
		result.wordWrap = wordWrap;
		result.fontSpec = fontSpec;
		result.lineHeight = lineHeight;
		result.textAlign = textAlign;
		return result;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
		markAsChanged();
	}

	public boolean isWordWrap() {
		return wordWrap;
	}

	public void setWordWrap(boolean wordWrap) {
		this.wordWrap = wordWrap;
		markAsChanged();
	}

	public FontSpec getFontSpec() {
		return fontSpec;
	}

	public void setFontSpec(FontSpec fontSpec) {
		this.fontSpec = fontSpec;
		markAsChanged();
	}

	public int getLineHeight() {
		return lineHeight;
	}

	public void setLineHeight(int lineHeight) {
		this.lineHeight = lineHeight;
	}

	@Override
	public HorizontalAlignmentConstant getHorizontalAlignment() {
		return textAlign;
	}

	@Override
	public void setHorizontalAlignment(HorizontalAlignmentConstant textAlign) {
		this.textAlign = textAlign;
	}

	@Override
	protected Widget createWidget() {
		widget = new Label(text, wordWrap);
		widget.getElement().getStyle().setOverflow(Overflow.HIDDEN);
		return widget;
	}

	@Override
	public void paintFrame(Graphics gc) {
		super.paintFrame(gc);
		if (isChanged()) {
			widget.setText(text);
			widget.setWordWrap(wordWrap);
			widget.setHorizontalAlignment(textAlign);
			fontSpec.applyTo(widget);
			Style widgetStyle = widget.getElement().getStyle();
			widgetStyle.setProperty("lineHeight",
					lineHeight + Unit.PCT.getType());
		}
	}

}
